//默认键值
import {serverConfig} from "../ApiAIChat.ts";

const KEY_CONVERSATION_LIST = "conversationList";
const KEY_NOW_CONVERSATION = "nowConversation";

//两个类型
export enum UserType {
    AI = "assistant",
    User = "user",
    Error = "error",
    System = "system"
}

//对话管理
export interface Conversation {
    name: string,//对话名
    key: string//标识key
}

//具体消息
export interface Message {
    role: UserType,//角色【AI|用户】
    content: string//消息内容
}

//生成一个对话的ID，确保不会重复
const generateID = (list: Conversation[]) => {
    let maxID = 0
    for (const i in list) {
        const nowID = Number(list[i].key.substring("conversation".length))
        if (nowID > maxID) {
            maxID = nowID
        }
    }
    return maxID + 1
}
//判断列表中是否有这个ID的对话
//获取对话的列表
export const getConversationList = (): Conversation[] => {
    const list = localStorage.getItem(KEY_CONVERSATION_LIST)
    if (list && list != "[]") {
        return JSON.parse(list)
    }
    const defaultConversationList = [{name: "默认会话", key: "conversation0"}]
    localStorage.setItem(defaultConversationList[0].key, "[]")
    localStorage.setItem(KEY_NOW_CONVERSATION, defaultConversationList[0].key)
    addMessageToConversation({role: UserType.System, content: serverConfig.message})
    localStorage.setItem(KEY_CONVERSATION_LIST, JSON.stringify(defaultConversationList))
    return defaultConversationList
}
//简单的获取ID，这里只是简单的实现，后面可以再做调整
export const getConversationKeyByID = (id: number) => {
    return "conversation" + id
}
//获取现在正在使用的Key
export const getNowConversationKey = () => {
    const key = localStorage.getItem(KEY_NOW_CONVERSATION)
    return key ? key : "";
}
//设置现在正在使用的Key
export const setNowConversationKey = (key: string) => {
    localStorage.setItem(KEY_NOW_CONVERSATION, key);
}
export const getDefaultNewConversationName = (): string => {
    return "新对话 " + (getConversationList().length + 1)
}
//增加新的对话
export const addNewConversation = (name: string, addSystem: boolean = false) => {
    //获取并解析json数组
    const json = localStorage.getItem(KEY_CONVERSATION_LIST)
    const list = JSON.parse(json ? json : "[]")
    //在后面加入新的对话项目
    const key = getConversationKeyByID(generateID(list))
    list.unshift({name: name, key: key})
    //设置初始为空对话
    localStorage.setItem(key, "[]")
    localStorage.setItem(KEY_CONVERSATION_LIST, JSON.stringify(list))
    //先设置现行对话
    setNowConversationKey(key)
    if (addSystem){
        addMessageToConversation({role: UserType.System, content: serverConfig.message})
    }
    return key
}
//删除某个对话
export const deleteConversation = (key: string) => {
    //移除对象
    localStorage.removeItem(key)
    //解析1json数组
    const json = localStorage.getItem(KEY_CONVERSATION_LIST)!
    const list = JSON.parse(json)
    //开始遍历
    const index = list.findIndex((conversationItem: Conversation) => conversationItem.key === key)
    if (index != -1) {
        list.splice(index, 1)
    }
    //设置回去
    localStorage.setItem(KEY_CONVERSATION_LIST, JSON.stringify(list))
}
export const setConversationNewName = (key: string, name: string) => {
    const list = getConversationList()
    list.forEach((conversationItem: Conversation) => {
        if (conversationItem.key === key) {
            conversationItem.name = name
        }
    })
    //设置回去
    localStorage.setItem(KEY_CONVERSATION_LIST, JSON.stringify(list))
}
//往某个会话中添加新的消息
export const addMessageToConversation = (message: Message) => {
    const key = getNowConversationKey()!
    //获取对话的列表
    const json = localStorage.getItem(key)
    const list = JSON.parse(json ? json : "[]")
    //添加新的对话进去
    list.push(message)
    localStorage.setItem(key, JSON.stringify(list))
}
//根据key值取得消息
export const getConversationMessages = (): Message[] => {
    const key = getNowConversationKey()
    const json = localStorage.getItem(key)
    return JSON.parse(json ? json : "[]")
}